/**
  * @description: 标注&&路线地图
  * @author: hj
  * @update: hj(2020-06-08)
  */

import React, { Component } from 'react';
import styles from './index.module.scss';
import { getMediaById } from '@/service/Api/Chart';
import { observer,inject,Provider } from 'mobx-react';
import './js/map.js'; // 创建地图
import "./index.css"



let map, markers = [], layerLines;
@inject('chartStore') 
@observer
class MarkerPointMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            params: [],
            data: [],
            forceFit: true, //forceFit自动试用宽度，默认false
            width: this.props.data.width ? this.props.data.width : '100%',   // 固定宽度    当自适应宽度开启，此功能失效
            height: this.props.data.height ? this.props.data.height : '100%',
            condition: this.props.data.condition ? this.props.data.condition : '',
            pageFlag: this.props.data.pageFlag ? this.props.data.pageFlag : '',
            nofirst: this.props.data.nofirst ? this.props.data.nofirst : '',
            color: this.props.data.color,
            title: '',
            chartId: this.props.data.chartId,
            id: this.props.data.componentId,
            chartData: [],
            axisArr: {},
            haveData: false,

            // 地图数据
            mapData: {
                area: '',
                data: []
            },

            dataNull: false, // 暂无数据

            // 全局变量
            mainData: [], // 操作组件可操作数据
            mainName: '', // 操作组件可操作当前维度
            mainFlag: false, // 是否是操作组件

            activeName: '', // 被选中车辆
            lines: [], // 轨迹路线
            
        };
    };


    componentWillMount() { //初始化
        const _this = this;

        console.log("markerLin")
        // 预览界面
        if (_this.state.pageFlag == 'preview') {
            // 判断当前组件是否是可操作组件
            const { globalData } = _this.props.chartStore;
            if (globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == _this.state.chartId) { // 可操作组件
                        let affectName = item.affectDimension;
                        _this.setState({
                            mainFlag: true,
                            mainName: affectName
                        })
                    }
                })
            }

            _this.interfaceRequest(_this.state.chartId,_this.state.condition);
        } else { // 配置面板
            if (_this.state.nofirst == 'nofirst') {
                _this.saveHandleData();
            } else {
                _this.interfaceRequest(_this.state.chartId,_this.state.condition);
            }
        }
    }

    // 钩子函数--组件挂载完成后
    componentDidMount() { //初始化
        this.setState({
            haveData: true
        })
    }
    // 接收父组件的数据改变
    componentWillReceiveProps = (nextProps) => {
        const _this = this;
        const { globalData, affectId } = _this.props.chartStore;

        // 预览界面---判断是否是变化组件
        if (nextProps.data.pageFlag == 'preview') {
            if (nextProps.data.condition != _this.state.requireCondition && globalData.slice().length > 0) {
                globalData.slice().map((item,index) => {
                    if (item.affect == affectId && item.require == nextProps.data.chartId) { // 联动组件
                        _this.setState({
                            pageInitFlag: false
                        })
                        let condition = {};
                        Object.keys(_this.state.requireCondition).forEach(function(keys){
                            condition[keys] = keys == item.requireDimension ? nextProps.data.condition[keys] : _this.state.requireCondition[keys];
                        })
                        _this.interfaceRequest(nextProps.data.chartId,condition);
                    }
                })
            }
        }
    }

    // 数据接口请求
    interfaceRequest = (chartId,condition) => {
        this.setState({
            requireCondition: condition,
        });

        let data = {
            charId: chartId,
            condition: condition
        };
        this.getMediaById(data);
    }

    // 数据存储刷新
    saveHandleData = () => {
        const { chartArrData } = this.props.chartStore;
        if (chartArrData.slice().length > 0) {
            chartArrData.slice().map((item) => {
                if (item.id == this.state.chartId) {
                    this.setState({
                        haveData: false
                    },function() {
                        // 数据处理
                        this.handleData(item.data);
                    })
                }
            })
        }
    }


    async getMediaById(data) {
        const res = await getMediaById(data);
        if (res.data && res.data.code === 0) {
            let str = res.data;
            if (str.data && str.data.data && str.data.data.length > 0) {
                // 存储图例原始数据
                const { saveChartData } = this.props.chartStore;
                let oldData = {
                    id: this.state.chartId,
                    data: str.data.data
                }
                saveChartData(oldData);

                // 数据处理
                this.handleData(str.data.data);
            } else {
                this.setState({
                    dataNull: true
                })
            }
        } else {
            this.setState({
                dataNull: true
            })
        }
    }
    // 数据处理
    handleData = (storeAllData) => {
        let storeData = storeAllData[0];
        this.setState({
            dataNull: true
        })

        // 非预览界面
        if (this.state.pageFlag != 'preview') {
            // 存储可操作组件数据
            if (storeData.affect && storeData.affect.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: storeData.title,
                    dimensionData: []
                }
                const { saveAffectData } = this.props.chartStore;

                let dimensionData = [];
                storeData.affect.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveAffectData(obj);
            }
            // 存储联动组件数据
            if (storeData.requires && storeData.requires.length > 0) {
                let obj = {
                    id: this.state.chartId,
                    label: storeData.title,
                    dimensionData: []
                }
                const { saveRequireData } = this.props.chartStore;

                let dimensionData = [];
                storeData.requires.slice().map((item,index) => {
                    dimensionData.push(item);
                })
                obj.dimensionData = dimensionData;
                saveRequireData(obj);
            }
        }

        // 页面初始化
        if (this.state.pageInitFlag) {
            if (storeData.affect &&  storeData.affect.length > 0) {
                this.setState({
                    affectName: storeData.affect[0]
                });
            }
            // 获取选择项
            if (storeData.conditionValues) {
                let selectData = storeData.conditionValues[storeData.affect[0]] ? storeData.conditionValues[storeData.affect[0]] : [];
                this.setState({
                    mainData: selectData
                });
            }
        }

        let oldData = storeData.data;
        let newData = [];
        oldData.slice().map((item,index) => {
            console.log("oldData",oldData,item)
            let obj = item;
            let lnglat = [];
            lnglat=item.lnglat.split(',');

            obj.name = item.name;
            obj.lnglat = lnglat;
            newData.push(obj);
        })
        console.log('GIS地图组件----newData=====', newData);
        
        let lines = storeData.line ? storeData.line : [];
        let name = lines.length > 0 ? lines[0].task_id : '';
        this.setState({
            title: storeData.title,
            chartData: newData,
            activeName: name,
            lines: lines,
            haveData: true,
        }, () => {
            this.drawMap();
        })
        // _this.drawMap();
    }
    


    // 绘制地图
    drawMap = () => {
        const _this = this;

        let mapId = 'chart_'+this.state.id+'_'+this.state.chartId;
        map = new AMap.Map(mapId, {
            mapStyle: 'https://amap://styles/darkblue',
            center: [104.06617,30.658426],
            // center: [116.397732, 39.912152],
            resizeEnable: true,
            zoom: 12,
        });
        layerLines = new Loca.LineLayer({
            map: map,
        });

        //ControlBar 插件
        // map.plugin(["AMap.ControlBar"],function(){
        //     var controlBar = new AMap.ControlBar({
        //         theme:"dark"
        //     })
        //     map.addControl(controlBar)
        // });


        AMapUI.loadUI(['control/BasicControl'], function(BasicControl) {

            var zoomCtrl1 = new BasicControl.Zoom({
                    theme: 'dark'
                })

            map.addControl(zoomCtrl1);

        });
        
        //地图鹰眼插件
        map.plugin(["AMap.OverView"],function(){
            var view = new AMap.OverView();
            map.addControl(view);
        }); 

        //比例尺
        map.plugin(["AMap.Scale"],function(){
            var scale = new AMap.Scale();
            map.addControl(scale);   
        });

        //地图操作工具条插件
        // map.plugin(["AMap.ToolBar"],function(){
        //     //加载工具条
        //     var tool = new AMap.ToolBar();
        //     map.addControl(tool);    
        // });

        const markerPosition = [104.008325, 30.669995]

        // 添加点标记
        _this.addMarker(markerPosition);
        // 添加线路
        _this.LineLayer();

        // 标注图层点击事件
        map.on('click', _this.showInfoClick);
    }
    // 地图点击事件
    showInfoClick = (e) => {
        // 改变全局变量
        // _this.onGlobalVariable();
        // 更新点标记
        this.addMarker();
        // 移除路线
        layerLines.setMap(null);
    }

    setMarkerImage=(type)=>{
        const iconImage={
            'company':require('./images/map_company.png'),
            'trailer':require('./images/map_truck.png'),
            'vehicle':require('./images/map_car.png')
        }
        return iconImage[type]||iconImage['company']
    }
    // 添加点标记
    addMarker = (value) => {
        const _this = this;
        // 删除点标记
        _this.removeMarkers();
        markers = [];

        // 添加maker
        // 构造点标记
        // let markerData = [
        //     {
        //         name: '川A32B75',
        //         lnglat: [103.962052,30.664778],
        //         markerType:'trailer'//'company','vehicle'
        //     }, {
        //         name: '川A22548',
        //         lnglat: [104.059555,30.732086]
        //     }, {
        //         name: '川A33204',
        //         lnglat: [104.030716,30.606879],

        //     }, {
        //         name: '川A13145',
        //         lnglat: [104.077408,30.400999]
        //     }, {
        //         name: '川ASB250',
        //         lnglat: [104.235336,30.741529]
        //     }
        // ]
        let markerData = _this.state.chartData;
        console.log("_this.state.chartData",_this.state.chartData)
        markerData.map((item,index) => {
            let marker;
            let color = '#ffffff';
            if (item.name == value) {
                color = '#07E8E4'
                let circleMarker = new AMap.CircleMarker({
                    center: item.lnglat,
                    // radius: 20+Math.random()*10,//3D视图下，CircleMarker半径不要超过64px
                    radius: 30,//3D视图下，CircleMarker半径不要超过64px
                    strokeColor: '#333333',
                    strokeWeight: 2,
                    strokeOpacity: 0.5,
                    fillColor: 'rgba(255,255,255,1)',
                    fillOpacity: 1,
                    zIndex: 10,
                    bubble: true,
                    cursor: 'pointer',
                    clickable: true
                })
                // circleMarker.setMap(map);
                markers.push(circleMarker);

    

                // 创建一个 icon
                let icon = new AMap.Icon({
                    size: new AMap.Size(30, 30),
                    image: iconImage[item.marker_type],
                    imageSize: new AMap.Size(30, 30),
                    imageOffset: new AMap.Pixel(0, 0)
                });

                // 将 icon 传入 marker
                marker = new AMap.Marker({
                    position: item.lnglat,
                    icon: icon,
                    anchor: 'center', //设置锚点
                    offset: new AMap.Pixel(0,0), //设置偏移量
                    label: {
                        content: "<div class='labelContent' style='color: "+ color +";font-size:16px;font-weight: 700'>"+item.name+"</div>",
                        offset: new AMap.Pixel(-15, -25)
                    },
                    clickable: true,
                    extData: item.name
                });
                // map.add(marker);
            } else {
                const iconImage={
                    'company':require('./images/map_company.png'),
                    'trailer':require('./images/map_truck.png'),
                    'vehicle':require('./images/map_car.png')
                }
                // const 
                // 创建一个 icon
                let icon = new AMap.Icon({
                    size: new AMap.Size(30, 30),
                    image: iconImage[item.marker_type],
                    imageSize: new AMap.Size(30, 30),
                    imageOffset: new AMap.Pixel(0, 0)
                });
                const markerImg=this.setMarkerImage(item.marker_type)
                marker = new AMap.Marker({
                    icon:markerImg,
                    position: item.lnglat,
                    anchor: 'center', //设置锚点
                    offset: new AMap.Pixel(0,0), //设置偏移量
                    label: {
                        content: `<div class='labelContent ${item.marker_type==="trailer"?"mappoint_trailer":""} ${item.marker_type==="company"?"mappoint_company":""} ${item.marker_type==="vehicle"?"mappoint_car":""}'>${item.name}</div>`,
                        offset: new AMap.Pixel(30, 5)
                    },
                    clickable: true,
                    extData: {name:item.name,orderId:item.order_id,dashbord_url:item.dashbord_url,video_url:item.video_url,marker_type:item.marker_type}
                });
                // map.add(marker);
            }
            markers.push(marker);

            // 监听marker点击事件
            AMap.event.addListener(marker, 'click', function(e) {
                let extData = e.target.getExtData();
                console.log("map click ", e, extData)
                if(extData.dashbord_url){
                    // this.props.history.push(extData.dashbord_url)
                    window.localStorage.setItem("markerExtdata",JSON.stringify(extData))
                    window.open(extData.dashbord_url)
                }
                // // 更新点标记
                // _this.addMarker(name);
                // // 显示线路
                // _this.LineLayer(name);

                // 改变全局变量
                _this.onGlobalVariable(name);
            });
        })
        map.add(markers);
    }
    // 删除点标记
    removeMarkers = () => {
        map.remove(markers);
    }
    // 添加线路
    LineLayer = (value) => {
        const _this = this;
        // 移除
        layerLines.setMap(null);

        // 添加线路
        let layer = new Loca.LineLayer({
            map: map,
        });

        console.log('_this.state.lines=====', _this.state.lines);
        layer.setData(_this.state.lines, {
            lnglat: 'lnglat'
        });
        layer.setOptions({
            style: {
                borderWidth: 5,
                opacity: 1,
                color: '#07E8E4',
            }
        });
        
        layer.render();
        // 添加至底图
        layer.setMap(map);
        layerLines = layer;
    }

    // 改变全局变量
    onGlobalVariable = (val) => {
        const { saveAffectId } = this.props.chartStore;
        saveAffectId(this.state.chartId);
        this.props.onGlobalVariable(val);
    }





    render() {
        const _this = this;
        const { endOpen } = _this.state;
        let Layer = this.props.layer;

        return (
            <div id={this.state.id+'_'+this.state.chartId} style={{ padding:"30px 20px 20px 20px", zIndex: 9999,width: this.state.width,height: this.state.height,overflow: 'hidden'}}>
                <Layer width={this.state.width} title={this.state.title} chartId={this.state.chartId} choiceData={this.state.mainData}></Layer>
                <div className={styles.mapBox}  id={'chart_'+this.state.id+'_'+this.state.chartId} style={{height: '100%'}}></div>
                <div className="legend_warp">
                  <div className="legend_item legend_company">
                    <div className="icon"></div>
                    拖运公司
                  </div>
                  <div className="legend_item legend_car">
                    <div className="icon"></div>
                    报废车
                  </div>
                  <div className="legend_item legend_tailer">
                    <div className="icon"></div>
                    拖运货车
                  </div>
                </div>
            </div>

        )
    }


}
export default MarkerPointMap;

